import { pageAllNovelUsingGet, pageNovelBySearchUsingGet } from "@/services/novel-web/novelController";
import { isAllBlank, isBlank } from "@/utils/stringUtils";
import { PageContainer } from "@ant-design/pro-components";
import { Input, List, message, Pagination } from "antd";
import { useEffect, useState } from "react";
import styles from "./index.less";
import { MessageError } from "@/utils/commonUtils";



const SearchPage: React.FC = () =>{

  const [data, setData] = useState<API.PageNovelVO_>();
  
  const loadAllData = async (
    page?: number,
    pageSize?: number
  )=>{
    try {
      const resp = await pageAllNovelUsingGet({
        current: page,
        pageSize: pageSize
      });
      setData(resp.data ?? undefined);
      
    } catch (error: any) {
      MessageError(error);
    }

  };

  const loadDataByKeys = async (
    tags: string,
    name: string,
    username: string,
    page?: number,
    pageSize?: number
  )=>{
    try {
      const resp = await pageNovelBySearchUsingGet({
        name: name,
        userName: username,
        tags: tags,
        current: page,
        pageSize: pageSize
      });
      setData(resp.data ?? undefined);
      
    } catch (error: any) {
      MessageError(error);
    }
  };

  useEffect(()=>{
    const urlParams = new URL(window.location.href).searchParams;
    const tagss = urlParams.get('tags') ?? '';
    const name = urlParams.get('name') ?? '';
    const username = urlParams.get('username') ?? '';
    if(!isAllBlank(tagss,name,username)) {
      loadDataByKeys(tagss,name,username);
    } else {
      loadAllData();
    }
  },[])


  // Input.Search
  const [value,setValue] = useState<string>('');
  const [tags,setTags] = useState<string>('');


  // BookCard
  const handleTagSearch = (tagId: number)=>{
    if(tagId <=0) return;
    loadDataByKeys(''+tagId,'','');
    setValue('');
    setTags(''+tagId);
  }

  // Pagination
  
  const handlePageCHange = (page: number, pageSize: number) =>{
    if(!isAllBlank(tags,value)) {
      loadDataByKeys(tags,value,value,page,pageSize);
    } else {
      loadAllData(page,pageSize);
    }
  }

  return (
    <PageContainer
      ghost
      content={
        <Input.Search
        className={styles.search}
        size="large"
        enterButton="搜索"
        allowClear
        value={value}
        onChange={(e)=>{
          setValue(e.target.value);
        }}
        onSearch={(value,_,info)=>{
          setValue(value);
          if(info?.source == 'clear' || isBlank(value)) {
            loadAllData();
          } else {
            loadDataByKeys('',value,value);
          }
        }}
      />
      }
    >
      <div className={styles.pageContainer}>
        <List
          className={styles.listContainer}
          // bordered
          grid={{column: 2}}
          dataSource={data?.records}
          renderItem={(novel) => (
            <List.Item>
              {/* BookCard */}
              <div className={styles.bookCard}>
                <img alt={novel.name} src={novel.cover} className={styles.cover} />
                <div className={styles.details}>
                  <div className={styles.title}>
                    <a href={"/novel/"+novel.id}>
                      {novel.name}
                    </a>
                  </div>
                  <div className={styles.author}>
                    作者: <a href={"/user/"+novel?.user?.id}>{novel.user?.nickname}</a>
                  </div>
                  <div className={styles.tags}>
                    标签: {novel.tags?.map((tag, index) => (
                      <span key={tag.id}>
                        {index != 0 && " / "}
                        <a 
                          onClick={()=>{
                            handleTagSearch(tag.id ?? 0);
                          }}
                        >{tag.name}</a>
                      </span>
                    ))}
                  </div>
                  <div className={styles.description}>{novel.description}</div>
                </div>
              </div>
              {/* end BookCard */}
            </List.Item>
          )}
        />
        
      </div>
      <Pagination
          className={styles.pagination}
          current={data?.current}
          total={data?.total}
          showSizeChanger={false}
          onChange={(page,pageSize)=> handlePageCHange(page,pageSize)}

        />
    </PageContainer>
   
  );

};


export default SearchPage;